//
//  VCPlayerManager.m
//  VCDemo
//
//  Created by 肖康龙 on 2018/3/8.
//  Copyright © 2018年 vsoontech. All rights reserved.
//

#import "VCPlayerManager.h"
#import "VCDowmload.h"
#import "VCDownloadManger.h"
//#import <SVProgressHUD/SVProgressHUD.h>



@interface VCPlayerManager ()<VCDownloadMangerDelegate>
//{
//    NSTimeInterval _currentPlaybackTime;
//}
///**视频的ID*/
//@property (nonatomic, strong)NSString *resourceID;
///**播放器*/
//@property (nonatomic,strong)id <IJKMediaPlayback> player;
///**背景图*/
//@property (nonatomic, strong)UIImageView *imageV_background;
//
///**播放器是否准备好*/
//@property (nonatomic,assign)BOOL isPlayerPrepareFinish;
///**是否暂停了播放*/
//@property (nonatomic,assign )BOOL isPause;
@end

@implementation VCPlayerManager
//
//+ (instancetype)defaultManager {
//    static id instance = nil;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        instance = [[self _alloc] _init];
//    });
//
//    if ([instance class] != [VCPlayerManager class]) {
//        NSCAssert(NO, @"该类不允许被继承");
//    }
//    return instance;
//}
//+(instancetype)alloc{
//    NSCAssert(NO, @"请使用`+defaultManager`方法获取实例");
//    return nil;
//}
//+(instancetype)allocWithZone:(struct _NSZone *)zone{
//    NSCAssert(NO, @"请使用`+defaultManager`方法获取实例");
//    return nil;
//}
//- (instancetype)init {
//    NSCAssert(NO, @"请使用`+defaultManager`方法获取实例");
//    return nil;
//}
//
//+ (instancetype)_alloc {
//    return [super allocWithZone:NSDefaultMallocZone()];
//}
//
//- (instancetype)_init {
//    if (self = [super init]) {
//        [VCDownloadManger DownloadManger].delegate = self;
//
////        /*回到前台*/
////        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
////        /*进入后台*/
////        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
//
//        /**监听是否触发home键挂起程序*/
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterBackground:)
//                                                     name:UIApplicationWillResignActiveNotification object:nil];
//        /**监听是否重新进入程序程序.*/
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground:)
//                                                     name:UIApplicationDidBecomeActiveNotification object:nil];
//    }
//
//    return self;
//}
//
//
//#pragma mark - set方法
///**设置playerLayer的填充模式*/
//-(void)setPlayerLayerGravity:(VCPlayerLayerGravity)playerLayerGravity{
//    _playerLayerGravity = playerLayerGravity;
//
//    if (playerLayerGravity == VCPlayerLayerGravityResize) {
//        [self.player setScalingMode:IJKMPMovieScalingModeFill];
//    }else if (playerLayerGravity == VCPlayerLayerGravityResizeAspect){
//        [self.player setScalingMode:IJKMPMovieScalingModeAspectFit];
//    }else if (playerLayerGravity == VCPlayerLayerGravityResizeAspectFill){
//        [self.player setScalingMode:IJKMPMovieScalingModeAspectFill];
//    }
//}
//
//#pragma mark - get方法
//-(UIImageView *)imageV_background{
//    if (_imageV_background == nil) {
//        _imageV_background = [[UIImageView alloc] init];
//        [self.playerView addSubview:_imageV_background];
//    }
//    return _imageV_background;
//}
//-(UIView *)playerView{
//    if (_playerView == nil) {
//        _playerView = [[UIView alloc] init];
//        _playerView.backgroundColor = [UIColor blackColor];
//        [_playerView addSubview:self.imageV_background];
//        //KVO 监听frame变化
//        [_playerView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
//    }
//    return _playerView;
//}
//
//-(NSTimeInterval)currentPlaybackTime{
//    NSNumber *firstSecNum = [[VCDownloadManger DownloadManger].dict objectForKey:@"firstSec"];
//    NSInteger firstSec = 0;
//    if (firstSecNum != nil) {
//        firstSec = [firstSecNum integerValue] * SecondsRatio;
//    }
//    _currentPlaybackTime = self.player.currentPlaybackTime + firstSec;
//    if (_currentPlaybackTime > self.duration) {
//        _currentPlaybackTime = self.duration;
//    }
//    return _currentPlaybackTime;
//}
//
///**
// *播放视频的id
// *也是启动播放器
// */
//-(void)downloadVideoWithId:(NSString *)linkId{
//    self.resourceID = linkId;
//    _duration = 0;
//    [[VCDownloadManger DownloadManger] downloadVideoWithId:self.resourceID Options:nil];//线上ID
//}
///**
// *调整播放时间(秒)
// */
//-(void)seekToTime:(NSTimeInterval)time{
//
//    UIImage *image = [self.player thumbnailImageAtCurrentTime];
//    if (image != nil) {
//        [self.imageV_background setImage:image];
//    }
//
//    [self.player pause];
//    [self clearPlayer];
//    [[VCDownloadManger DownloadManger] setCurrentPlaybackTime:time*MillisecondsRatio];
//}
///**
// *暂停播放
// */
//-(void)pause{
//    self.isPause = YES;
//    [self.player pause];
//}
///**
// *开始播放
// */
//-(void)play{
//    self.isPause = NO;
//    [self.player play];
//}
///**
// *停止播放,停止播放会销毁播放资源,需要重新开启下载器
// */
//-(void)stop{
//    [self clearPlayer];//清除播放器
//    [self.imageV_background removeFromSuperview];
//    self.imageV_background = nil;
//    [[VCDownloadManger DownloadManger] stopDownload];
//}
//
//
//
//
//
//#pragma mark - 监听和通知
//-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
//    if ([keyPath isEqualToString:@"frame"]) {//playerLayer的frame有改变
//        CGSize size = [[change objectForKey:NSKeyValueChangeNewKey] CGRectValue].size;
//        //先创建视频播放器的View
//        UIView *playerView = [self.player view];
//        playerView.frame = CGRectMake(0, 0, size.width, size.height);
//        self.imageV_background.frame = CGRectMake(0, 0, size.width, size.height);
//    }
//}
//
//
//#pragma mark - 播放器操作
///**创建播放器*/
//-(void)createPlayerWithUrl:(NSString *)urlString{
//    IJKFFOptions *options = [IJKFFOptions optionsByDefault];
////    //硬解1
////    [options setPlayerOptionIntValue:1 forKey:@"videotoolbox"];
////    [options setOptionIntValue:1 forKey:@"videotoolbox" ofCategory:kIJKFFOptionCategoryPlayer];
////    // 最大fps
////    [options setPlayerOptionIntValue:30 forKey:@"max-fps"];
//
//    //解码参数，画面更清晰
//    [options setCodecOptionIntValue:IJK_AVDISCARD_DEFAULT forKey:@"skip_loop_filter"];
////    [options setCodecOptionIntValue:IJK_AVDISCARD_DEFAULT forKey:@"skip_frame"];
//
//    //设置缓存大小，太大了没啥用,太小了视频就处于边播边加载的状态，目前是10M，后期可以调整
//    [options setPlayerOptionIntValue:5* 1024 *1024 forKey:@"max-buffer-size"];
//    //播放前的探测时间
////    [options setFormatOptionIntValue:10000 forKey:@"analyzeduration"];
//
//    self.player = [[IJKFFMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:urlString] withOptions:options];
//
//    [self.player setPauseInBackground:YES];
//    [self.player setScalingMode:IJKMPMovieScalingModeAspectFit];
//    [self.player prepareToPlay];//设置为准备好就播放
//
//    //添加通知方法
//    [self addPlayerNoti];
//
//    //先创建视频播放器的View
//    UIView *playerView = [self.player view];
//    playerView.frame = self.playerView.bounds;
//    //设置大小
//    [self.playerView insertSubview:playerView atIndex:1];
//}
//
///**清除播放器*/
//-(void)clearPlayer{
//    self.isPlayerPrepareFinish = NO;
//    [self removePlayerNoti];
//    [self.player.view removeFromSuperview];
//    [self.player shutdown];
//    self.player = nil;
//}
//
///**添加播放器通知*/
//- (void)addPlayerNoti {
//
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(loadStateDidChange:)
//                                                 name:IJKMPMoviePlayerLoadStateDidChangeNotification
//                                               object:_player];
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(moviePlayBackFinish:)
//                                                 name:IJKMPMoviePlayerPlaybackDidFinishNotification
//                                               object:_player];
//
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(mediaIsPreparedToPlayDidChange:)
//                                                 name:IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification
//                                               object:_player];
//
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(moviePlayBackStateDidChange:)
//                                                 name:IJKMPMoviePlayerPlaybackStateDidChangeNotification
//                                               object:_player];
//
//}
//
//
///**去除播放器通知*/
//-(void)removePlayerNoti{
//    [[NSNotificationCenter defaultCenter] removeObserver:self
//                                                    name:IJKMPMoviePlayerLoadStateDidChangeNotification
//                                                  object:_player];
//    [[NSNotificationCenter defaultCenter] removeObserver:self
//                                                    name:IJKMPMoviePlayerPlaybackDidFinishNotification
//                                                  object:_player];
//    [[NSNotificationCenter defaultCenter] removeObserver:self
//                                                    name:IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification
//                                                  object:_player];
//    [[NSNotificationCenter defaultCenter] removeObserver:self
//                                                    name:IJKMPMoviePlayerPlaybackStateDidChangeNotification
//                                                  object:_player];
//
//}
//
//
//#pragma mark - 播放器的通知监听
///**播放器准备完成,可以播放*/
//- (void)mediaIsPreparedToPlayDidChange:(NSNotification*)notification {
//    NSLog(@"加载 可以播放mediaIsPrepareToPlayDidChange");
//    self.isPlayerPrepareFinish = YES;
//}
///**播放器加载状态改变*/
//- (void)loadStateDidChange:(NSNotification*)notification
//{
//    IJKMPMovieLoadState loadState = self.player.loadState;
//    if ((loadState & IJKMPMovieLoadStatePlaythroughOK) !=0) {
//        NSLog(@"加载状态变成了已经缓存完成，如果设置了自动播放，这时会自动播放");
//    }
//    if ((loadState & IJKMPMovieLoadStateStalled) != 0)
//    {
//        NSLog(@"加载状态变成了数据缓存已经停止，播放将暂停");
//    }
//    if((loadState & IJKMPMovieLoadStatePlayable) != 0)
//    {
//        NSLog(@"加载状态变成了缓存数据足够开始播放，但是视频并没有缓存完全");
//    }
//    if ((loadState & IJKMPMovieLoadStateUnknown) != 0) {
//        NSLog(@"加载状态变成了未知状态");
//    }
//
//    if ([self.delegate respondsToSelector:@selector(PlayerloadStateChanged:)]) {
//        [self.delegate PlayerloadStateChanged:(VCMPMovieLoadState)self.player.loadState];
//    }
//}
///**播放器播放状态改变*/
//- (void)moviePlayBackStateDidChange:(NSNotification*)notification
//{
//    IJKMPMoviePlaybackState nelpLoadState = self.player.playbackState;
//
//    if (nelpLoadState == IJKMPMoviePlaybackStatePlaying){//可以播放
//
//    }else{ //缓冲
//
//    }
//    NSLog(@"%@",NSStringFromCGSize(self.player.naturalSize));
//    NSLog(@"");
//    switch (_player.playbackState) {
//        case IJKMPMoviePlaybackStateStopped:
//
//            NSLog(@"加载播放器的播放状态变了，现在是停止状态:%d",(int)_player.playbackState);
//            break;
//        case IJKMPMoviePlaybackStatePlaying:
//
//            NSLog(@"加载播放器的播放状态变了，现在是播放状态:%d",(int)_player.playbackState);
//            break;
//        case IJKMPMoviePlaybackStatePaused:
//            NSLog(@"加载播放器的播放状态变了，现在是暂停状态:%d",(int)self.player.playbackState);
//            break;
//        case IJKMPMoviePlaybackStateInterrupted:
//            NSLog(@"加载播放器的播放状态变了，现在是中断状态:%d",(int)self.player.playbackState);
//            break;
//        case IJKMPMoviePlaybackStateSeekingForward:
//            NSLog(@"加载播放器的播放状态变了，现在是向前拖动状态:%d",(int)self.player.playbackState);
//
//            break;
//        case IJKMPMoviePlaybackStateSeekingBackward:
//            NSLog(@"加载播放器的播放状态变了，现在是向后拖动状态：%d",(int)self.player.playbackState);
//            break;
//        default:
//            NSLog(@"加载播放器的播放状态变了，现在是未知状态：%d",(int)self.player.playbackState);
//            break;
//    }
//    if ([self.delegate respondsToSelector:@selector(PlayerPlayStateChanged:)]) {
//        [self.delegate PlayerPlayStateChanged:(VCMPMoviePlaybackState)self.player.playbackState];
//    }
//}
///**播放器播放播放完成通知*/
//- (void)moviePlayBackFinish:(NSNotification*)notification
//{
//    NSLog(@"播放器播放结束,结束原因 = %@",notification.userInfo);
//    UIImage *image = [self.player thumbnailImageAtCurrentTime];
//    if (image != nil) {
//        [self.imageV_background setImage:image];
//    }
//    if ([self.delegate respondsToSelector:@selector(moviePlayBackFinishWithReason:)]) {
//        [self.delegate moviePlayBackFinishWithReason:notification.userInfo];
//    }
//    if ([[notification.userInfo objectForKey:@"IJKMPMoviePlayerPlaybackDidFinishReasonUserInfoKey"] intValue] == 0 && ![VCInformationTool getVideoIsLastTs]) {//判断播放器断开了,并且ts并没有播放完毕
//        [VCInformationTool setPlayerIsRestart:YES];
//
//        [VCDownloadManger DownloadManger].isReturnAdd = NO;
//
//        [[VCDownloadManger DownloadManger] openServer];//启动服务器
//        [self clearPlayer];//清除之前播放器
////        [self createPlayerWithUrl:[VCDownloadManger DownloadManger].urlString];//创建播放器
//    }else{
//        [self clearPlayer];//清除之前播放器
//        [[VCDownloadManger DownloadManger] stopDownload];
//    }
//
////    [SVProgressHUD showImage:nil status:@"播放器播放播放完成通知"];
////    [SVProgressHUD setCornerRadius:5.0f];
////    [SVProgressHUD setMinimumSize:CGSizeMake(100, 15)];
////    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
////    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
////        [SVProgressHUD dismiss];
////    });
//
//}
//#pragma mark - 通知
///**回到前台*/
//-(void)willEnterForeground:(NSNotification *)noti{
//    if (self.player != nil && !self.isPause) {
//        [self.player play];
//    }
//}
///**进入后台*/
//-(void)willEnterBackground:(NSNotification *)noti{
//    if (self.player != nil) {
//        [self.player pause];
//    }
//}
//
//
//
//#pragma mark - VCDownloadMangerDelegate
///**
// *url :播放地址
// */
//-(void)download:(VCDownloadManger *)dounload url:(NSString *)url{
//    NSNumber *videoDuration= [[VCDownloadManger DownloadManger].dict objectForKey:@"videoDuration"];//毫秒
//    if (videoDuration != nil) {
//        _duration = [videoDuration floatValue] * SecondsRatio;//返回的是秒
//    }
//
//
//    [self clearPlayer];//清除之前播放器
//    [self createPlayerWithUrl:url];//创建播放器
//
//}
///**
// *url :播放地址
// */
//-(void)download:(VCDownloadManger *)dounload player:(VCPlayerManager *)player{
//
//}
//
///**
// *返回播放器的缓冲时间(秒)
// */
//-(NSTimeInterval)playerBufferTimeWithdownload:(VCDownloadManger *)dounload{
//    VCNSLog(@"播放器的缓存时间 %ld   当前播放的时间 %lf    总的时间 %lf   播放时间 %lf",(long)self.player.bufferingProgress,self.player.currentPlaybackTime,self.player.duration,self.player.playableDuration);
//    NSTimeInterval playerBuffering = (self.player.playableDuration - self.player.currentPlaybackTime);
//    if (playerBuffering<0) playerBuffering = 0;
//    return playerBuffering;
//}
@end
